package com.xncoding.trans.aspect;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import com.xncoding.trans.annotate.RedisCache;
import com.xncoding.trans.hannder.RedisCacheHandler;
import com.xncoding.trans.hannder.RedisCacheProvider;
/**
 * @CreateAt: 2023-11-3 11:27:20
 * @ModifyAt: 2023-11-3 11:27:20
 * @Version 1.0
 */
@Aspect
@Slf4j
@Component
@AllArgsConstructor
public class RedisCacheAspect {
    @Pointcut("@annotation(com.xncoding.trans.annotate.RedisCache)")
    public void annotationPoint() throws Throwable {
    }
    private RedisCacheProvider redisCacheProvider;
    /**
     * 却面切入点
     * implements Serializable 对象需要继承
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    @Around(value = "annotationPoint()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        try {
            MethodSignature method = (MethodSignature) proceedingJoinPoint.getSignature();
            RedisCache redisCache = method.getMethod().getAnnotation(RedisCache.class);
            Object[] args = proceedingJoinPoint.getArgs();
            RedisCacheHandler apply = redisCacheProvider.apply(redisCache.type());
            Boolean hasKey = apply.existHandler(args, redisCache.key());
            if (hasKey) {
                return apply.queryHandler(args, redisCache.key());
            } else {
                Object result = proceedingJoinPoint.proceed();
                apply.handler(redisCache.type(), args, result, redisCache.time(), redisCache.timeType(), redisCache.key());
                return result;
            }
        } catch (Exception e) {
            System.out.println("RedisCacheAspect Error:{}"+ e.toString());
            return proceedingJoinPoint.proceed();
        }
    }
}